package com.lgmshare.k3.http.base;

import android.os.Build;
import android.text.TextUtils;

import com.lgmshare.component.utils.UIUtils;
import com.lgmshare.k3.K3Config;

/**
 * Created by LiBinWen on 2015/12/15.
 */
final class Utils {

    static String userAgent;

    /**
     * 获取User-Agent
     */
    public static String getUserAgent() {
        if (!TextUtils.isEmpty(userAgent)) {
            return userAgent;
        }
        //"1.5.8/iPhone/iOS 8.1.1/2.00/iPhone 5S";
        String versionSDK = Build.VERSION.RELEASE;
        //OKHttp中User-Agent里面不能包含中文
        String phoneName = chineseToASCII(Build.MODEL);
        int width = UIUtils.getDisplayWidth();
        int height = UIUtils.getDisplayHeight();
        StringBuffer sb = new StringBuffer(80);
        sb.append('"');
        sb.append("K3APP ");
        sb.append(K3Config.INTERFACE_VERSION);
        sb.append("/");
        sb.append("android ");
        sb.append(versionSDK);
        sb.append("/");
        sb.append(width + "," + height);
        sb.append("/");
        sb.append(phoneName);
        sb.append('"');
        userAgent = sb.toString();
        return userAgent;
    }

    /**
     * 中文转ASCII码
     *
     * @param str
     * @return
     */
    public static String chineseToASCII(String str) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = str.length(); i < length; i++) {
            char c = str.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
